package com.example.mq.server.virtualhost;

import com.example.mq.server.consumermanager.ConsumerEnv;

import java.util.ArrayList;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class MQueue {
    private String name; // 唯一身份标识.

    // 已被哪些消费者订阅了
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    // 记录当前取到了第几个消费者. 以实现轮询策略
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    // 添加一个新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }

    // 轮询 处理每个已订阅的消费者
    public ConsumerEnv chooseConsumer() {
        if (consumerEnvList.size() == 0) {
            // 该队列没有人订阅的
            return null;
        }
        // 计算一下当前要取的元素的下标
        int index = consumerSeq.get() % consumerEnvList.size();

        consumerSeq.getAndIncrement();

        return consumerEnvList.get(index);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<ConsumerEnv> getConsumerEnvList() {
        return consumerEnvList;
    }

    public void setConsumerEnvList(List<ConsumerEnv> consumerEnvList) {
        this.consumerEnvList = consumerEnvList;
    }
}
